//
//  TearOpenView.m
//  us
//
//  Created by karry on 2025/4/28.
//

#import "TearOpenView.h"

@interface TearOpenView()

@property (nonatomic,strong) CAShapeLayer *lineLayer;
@property (nonatomic,strong) UIImageView *cutImageView;
@property (nonatomic, assign) CGFloat lastFeedbackY;
@property (nonatomic, strong) UIImpactFeedbackGenerator *feedbackGenerator;
@property (nonatomic,strong) CAShapeLayer *fillLineLayer;
@property (nonatomic) BOOL hasTriggered;

@property (nonatomic,strong) UIImageView *leftContentImageView;

@end

@implementation TearOpenView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setupView];
    }
    return self;
}

- (void)setupView{
    
    self.feedbackGenerator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
    [self.feedbackGenerator prepare];
    self.lastFeedbackY = self.cutImageView.center.y;
    
    
    UIImage *image = [UIImage imageNamed:@"ic_left_day"];

    // 1️⃣ 计算图片中间的 capInsets（留出四周边距）
    UIEdgeInsets insets = UIEdgeInsetsMake(image.size.height / 2 - 1,
                                           image.size.width / 2 - 1,
                                           image.size.height / 2 - 1,
                                           image.size.width / 2 - 1);

    // 2️⃣ 创建可拉伸图片
    UIImage *resizableImage = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    
    self.leftImageView = [[UIImageView alloc]initWithImage:resizableImage];
    [self addSubview:self.leftImageView];
    
    self.rightImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_right_day"]];
    [self addSubview:self.rightImageView];
    
    [self.leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.top.mas_offset(0);
    }];
    
    [self.rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.top.mas_offset(0);
        make.width.mas_equalTo(62);
        make.left.mas_equalTo(self.leftImageView.mas_right);
    }];
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    CGFloat lineW = 3;
    CGFloat left = self.jk_width - 62;
    [path moveToPoint:CGPointMake(left, 6)];
    [path addLineToPoint:CGPointMake(left, self.jk_height - 6)];
    
    self.lineLayer = [CAShapeLayer layer];
    self.lineLayer.path = path.CGPath;
    self.lineLayer.lineWidth = lineW;
    self.lineLayer.lineDashPattern = @[@4, @4]; // 实线长度为4，间隔为2
    self.lineLayer.lineCap = kCALineCapButt;    // 线端样式，kCALineCapRound更圆滑
    self.lineLayer.strokeColor = [[UIColor mi_3_color] jk_darkenColor:0.1].CGColor;
    [self.layer addSublayer:self.lineLayer];
    
    self.fillLineLayer = [CAShapeLayer layer];
    self.fillLineLayer.lineWidth = lineW;
    self.fillLineLayer.strokeColor = [UIColor mi_2_color].CGColor;
    [self.layer addSublayer:self.fillLineLayer];
    
    self.cutImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"scissors 1"]];
    [self addSubview:self.cutImageView];
    [self.cutImageView sizeToFit];
    
    self.cutImageView.center = CGPointMake(left, 6);
    
    self.cutImageView.userInteractionEnabled = YES;
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanGesture:)];
    [self.cutImageView addGestureRecognizer:panGesture];
    
    self.leftContentImageView =  [[UIImageView alloc]initWithImage:resizableImage];
    self.leftContentImageView.contentMode = UIViewContentModeScaleToFill;
    [self insertSubview:self.leftContentImageView atIndex:0];
    [self.leftContentImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.leftImageView);
    }];
    
    UILabel *contentLab = [[UILabel alloc]init];
    contentLab.font = [UIFont systemFontOfSize:15];
    contentLab.textColor = UIColor.secondaryLabelColor;
    contentLab.numberOfLines = 0;
    self.contentLab = contentLab;
    [self.leftContentImageView addSubview:contentLab];
    
    [contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(16);
        make.right.bottom.mas_offset(-16);
    }];
    
    
    UILabel *titleLab = [UILabel new];
    titleLab.font = [UIFont systemFontOfSize:20 weight:UIFontWeightSemibold];
    titleLab.text = @"有新问答✨";
    [self.leftImageView addSubview:titleLab];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.leftImageView);
        make.bottom.mas_equalTo(self.leftImageView.mas_centerY);
    }];
    
    UILabel *infoLab = [UILabel new];
    infoLab.textAlignment = NSTextAlignmentCenter;
    infoLab.font = [UIFont systemFontOfSize:15];
    infoLab.text = @"向下剪开右边封条查看问题";
    infoLab.textColor = UIColor.secondaryLabelColor;
    [self.leftImageView addSubview:infoLab];
    [infoLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.right.mas_offset(-16);
        make.top.mas_equalTo(titleLab.mas_bottom).mas_offset(8);
    }];
    
    
    
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)gesture {
 
    if (self.hasTriggered) {
        return;
    }
    
    CGPoint translation = [gesture translationInView:self];
    CGFloat newY = self.cutImageView.center.y + translation.y;
    
    // 限制范围
    newY = MAX(6, MIN(self.jk_height - 6, newY));
    self.cutImageView.center = CGPointMake(self.cutImageView.center.x, newY);
    
    [self upLineAtPoint:self.cutImageView.center];
    
    [gesture setTranslation:CGPointZero inView:self];
    
    // 每隔 N pt 触发一次震动
    CGFloat interval = 10.0; // 间隔越小，反馈越频繁
    if (fabs(newY - self.lastFeedbackY) >= interval) {
        [self.feedbackGenerator impactOccurred];
        [self.feedbackGenerator prepare]; // 准备下一次
        AudioServicesPlaySystemSound(1104);
        self.lastFeedbackY = newY;
    }
    
    // 滑动到底部时触发 block（只触发一次）
    if (gesture.state == UIGestureRecognizerStateChanged || gesture.state == UIGestureRecognizerStateEnded) {
        if (newY >= self.jk_height - 6) {
            [USFeedbackTool impactHeavy];
            [self tearLeftImageViewIntoSquares];
            _hasTriggered = YES;
        }

    }
    
}

- (void)tearLeftImageViewIntoSquares {
    if (self.didReachBottomBlock) {
        self.didReachBottomBlock();//触发领取
    }
    
    UIView *view = self.leftImageView;
    NSInteger rows = 8;
    NSInteger cols = 6;

    CGSize size = view.bounds.size;
    CGFloat tileW = size.width / cols;
    CGFloat tileH = size.height / rows;

    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    view.hidden = YES;

    dispatch_group_t group = dispatch_group_create();

    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            CGRect tileRect = CGRectMake(col * tileW, row * tileH, tileW, tileH);
            CGImageRef tileImageRef = CGImageCreateWithImageInRect(fullImage.CGImage, tileRect);
            UIImage *tileImage = [UIImage imageWithCGImage:tileImageRef];
            CGImageRelease(tileImageRef);

            UIImageView *tileView = [[UIImageView alloc] initWithImage:tileImage];
            tileView.frame = CGRectMake(view.frame.origin.x + tileRect.origin.x,
                                        view.frame.origin.y + tileRect.origin.y,
                                        tileW,
                                        tileH);
            [self addSubview:tileView];

            // 动画参数
            CGFloat duration = 0.8 + (arc4random_uniform(100) / 200.0); // 0.8 ~ 1.3 秒
            CGFloat angle = ((arc4random_uniform(360)) / 180.0) * M_PI;
            CGFloat offsetX = arc4random_uniform(80) - 40;
            CGFloat offsetY = arc4random_uniform(150) + 100;

            dispatch_group_enter(group);

            [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
                tileView.transform = CGAffineTransformMakeRotation(angle);
                tileView.frame = CGRectOffset(tileView.frame, offsetX, offsetY);
                tileView.alpha = 0;
                self.cutImageView.alpha = 0;
            } completion:^(BOOL finished) {
                [tileView removeFromSuperview];
                dispatch_group_leave(group);
            }];
        }
    }

    // 所有动画完成后回调
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (self.tearCompletedBlock) {
            self.tearCompletedBlock();
        }
    });
}

- (void)upLineAtPoint:(CGPoint)point{
    
    CGFloat left = self.jk_width - 62;
    
    UIBezierPath *path0 = [UIBezierPath bezierPath];
    [path0 moveToPoint:CGPointMake(left, 0)];
    [path0 addLineToPoint:CGPointMake(left, point.y)];
    self.fillLineLayer.path = path0.CGPath;
 
    
}




@end
